package cc.miwuya.common.util.exception;

import cc.miwuya.common.util.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * @Author 迷雾森林
 * @Date 2024-01-08 21:29
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(value = HubException.class)
    public Result handler(HubException e){
        log.error("自定义异常 ---- {}",e.getMessage());
        return Result.error(HttpStatus.BAD_REQUEST.value(),e.getMessage());
    }

    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(value = RuntimeException.class)
    public Result handler(RuntimeException e){
        log.error("运行时异常 ---- {}",e.getMessage());
        return Result.error(HttpStatus.BAD_REQUEST.value(),e.getMessage());
    }

//    @ResponseStatus(HttpStatus.NOT_FOUND)
//    @ExceptionHandler(value = NoHandlerFoundException.class)
//    public Result handler(NoHandlerFoundException e){
//        log.error("404异常 ---- {}",e.getMessage());
//        return Result.error(HttpStatus.NOT_FOUND.value(),e.getMessage());
//    }

    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public Result handler(MethodArgumentNotValidException e){
        BindingResult bindingResult = e.getBindingResult();
        ObjectError objectError = bindingResult.getAllErrors().stream().findFirst().get();
        log.error("实体校验异常 ---- {}",objectError.getDefaultMessage());
        return Result.error(HttpStatus.BAD_REQUEST.value(),objectError.getDefaultMessage());
    }
}
